package cn.zhaoyuening.chat_server.server;

import cn.zhaoyuening.chat_common.utils.MarshallingCodeCFactory;
import cn.zhaoyuening.chat_server.container.ChannelContainer;
import cn.zhaoyuening.chat_server.handler.ChatServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * Created by Buynow on 2017/6/14.
 * 聊天TCP服务器
 */
@Component
public class ChatServer implements Runnable{
    @Value("${chat_server.port}")
    private int port;
    @Autowired
    private ChannelContainer container;



    public ChatServer(){
        this.port = port;
    }

    @Override
    @PostConstruct
    public void run() {
        EventLoopGroup parentGroup = new NioEventLoopGroup();
        EventLoopGroup childGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(parentGroup, childGroup);
        bootstrap.channel(NioServerSocketChannel.class);
        bootstrap.option(ChannelOption.SO_BACKLOG, 128);
        //通过NoDelay禁用Nagle,使消息立即发出去，不用等待到一定的数据量才发出去
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        //保持长连接状态
        bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
                ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
                ch.pipeline().addLast(new ChatServerHandler(container));
            }
        });
        try {
            ChannelFuture future = bootstrap.bind(port).sync();
            System.out.println("chat server started!");
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            parentGroup.shutdownGracefully();
            childGroup.shutdownGracefully();
        }
    }

    public void setPort(int port) {
        this.port = port;
    }

    public void setContainer(ChannelContainer container) {
        this.container = container;
    }
}
